#coding=utf-8
from django.db import models
from eday import Eday

class Price(models.Model):
    eday = models.OneToOneField(Eday)
       
    start = models.FloatField(null=True, blank=True)
    end = models.FloatField()
    
    low = models.FloatField(null=True, blank=True)
    high = models.FloatField(null=True, blank=True)
    
    volume = models.IntegerField()  
    amount = models.IntegerField()
    
    change = models.FloatField(null=True, blank=True)
    hsl = models.FloatField(null=True, blank=True)
    fluctuation = models.FloatField(null=True, blank=True)
    jump = models.FloatField(null=True, blank=True)
    
    def get_change(self):
        '''涨跌'''  
        pre = self.eday.pre
        if not pre:return None
        
        pe = pre.price.end
        change = ( self.end - pe )/ pe * 100
        return change
    
    def get_hsl(self):
        '''换手率'''
        ts = self.eday.ts
        if not ts:
            return None
        hsl = self.volume / float(ts) * 100
        return hsl
        
    def get_fluctuation(self):
        '''波动幅度'''
        try:
            f = ( self.high - self.low ) / self.end * 100
            return f
        except AttributeError:
            return None
    
    def get_jump(self):
        '''跳空?'''
        pre = self.eday.pre
        if not pre:return None
        
        pre_end = pre.price.end
        jump = (self.start - pre_end)/pre_end * 100
        return jump
          
    def save(self):
        self.change = self.get_change()   
        self.hsl = self.get_hsl()
        self.fluctuation = self.get_fluctuation()
        self.jump = self.get_jump()
        super(Price, self).save()
    
    def get_date(self):
        return self.eday.date.isoformat()
    date = property(fget=get_date)
    
    def __unicode__(self):
        e = self.eday
        return "(%s:%s):%.2f"%(e.finance_tool.name, e.date, e.price.end)
        
    class Meta:
        app_label = 'data'
